"""
智慧医院资源调度与预约优化平台
主应用入口
"""

from flask import Flask
from app import create_app, db
from app.models import User, Department, Resource, Appointment
import os

# 创建应用实例
app = create_app()

@app.shell_context_processor
def make_shell_context():
    """Shell上下文处理器"""
    return {
        'db': db,
        'User': User,
        'Department': Department,
        'Resource': Resource,
        'Appointment': Appointment
    }

def init_database():
    """初始化数据库"""
    with app.app_context():
        # 创建所有表
        db.create_all()
        
        # 创建默认管理员用户
        if not User.query.filter_by(username='admin').first():
            from werkzeug.security import generate_password_hash
            admin = User(
                username='admin',
                email='admin@hospital.com',
                password_hash=generate_password_hash('admin123'),
                role='admin',
                phone='13800138000'
            )
            db.session.add(admin)
        
        # 创建默认科室
        if not Department.query.first():
            departments = [
                {'name': '内科', 'description': '内科疾病诊疗'},
                {'name': '外科', 'description': '外科手术诊疗'},
                {'name': '妇科', 'description': '妇科疾病诊疗'},
                {'name': '儿科', 'description': '儿童疾病诊疗'},
                {'name': '急诊科', 'description': '急诊诊疗'},
            ]
            
            for dept_data in departments:
                department = Department(**dept_data)
                db.session.add(department)
        
        # 创建默认资源
        if not Resource.query.first():
            resources = [
                {'name': '内科诊室1', 'resource_type': 'consultation_room', 'department_id': 1, 'capacity': 1, 'location': '1楼101'},
                {'name': '内科诊室2', 'resource_type': 'consultation_room', 'department_id': 1, 'capacity': 1, 'location': '1楼102'},
                {'name': '外科手术室1', 'resource_type': 'operating_room', 'department_id': 2, 'capacity': 1, 'location': '2楼201'},
                {'name': '外科手术室2', 'resource_type': 'operating_room', 'department_id': 2, 'capacity': 1, 'location': '2楼202'},
                {'name': 'CT检查室', 'resource_type': 'equipment', 'department_id': 1, 'capacity': 1, 'location': '1楼103'},
                {'name': 'MRI检查室', 'resource_type': 'equipment', 'department_id': 1, 'capacity': 1, 'location': '1楼104'},
            ]
            
            for resource_data in resources:
                resource = Resource(**resource_data)
                db.session.add(resource)
        
        db.session.commit()
        print("数据库初始化完成")

if __name__ == '__main__':
    # 初始化数据库
    init_database()
    
    # 启动应用
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=True
    )
